function [shape] = poly_rotate2(varargin)
%% Poly Rotate 2
%       Rotate a given polygon in 'shape' about the location [x,y] by angle
%       a (in degrees).
%
%       poly_rotate2(shape,x,y,a) - Rotate the fill shape defined in
%       'shape' by 'a' degrees about point [x,y].
%
%       poly_rotate2(shape,a) - Rotate the fill shape defined in 'shape' by
%       'a' degrees. 

%%
% Determine if shape is a legit x,y matrix
test=size(varargin{1});
if (test(1,2) ~= 2)
    error('>>> Shape must be of size [n,2]')
    % RETURN
end

%%
tmp = size(varargin);
if tmp(1,2)==2
    % Calculate the center of the shape for x,y
    shape = varargin{1};
    a = varargin{2};
    
    tmp2 = size(shape);
    tmp3 = sum(shape)./tmp2(1,1);
    
    x = tmp3(1,1);
    y = tmp3(1,2);

elseif tmp(1,2)==4
    % Set the variable names
    shape = varargin{1};
    x = varargin{2};
    y = varargin{3};
    a = varargin{4};
else
    error('>>> Useage poly_rotate(shape,[x,y],a)');
    % RETURN
end

%% Clean up
clear tmp;
clear tmp2;
clear tmp3;

%% Sanity check
% shape
% x
% y
% a

%%
% Convert a to degrees
a = a*pi/180;

% Move matrix to origin of point
shape(:,1)=shape(:,1)-x;
shape(:,2)=shape(:,2)-y;

% Preform rotation
rot = [cos(a),-sin(a);sin(a),cos(a)];
shape = shape*rot;

% Return shape to location
shape(:,1)=shape(:,1)+x;
shape(:,2)=shape(:,2)+y;
end